package com.example.test.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.test.domain.SnEquip;
import com.example.test.domain.SnPerson;
import com.example.test.enums.AddStatusEnums;
import com.example.test.enums.ClearStatusEnums;
import com.example.test.enums.UploadStatusEnums;
import com.example.test.mapper.SnEquipMapper;
import com.example.test.mapper.SnPersonMapper;
import com.example.test.service.IFaceRecognitionService;
import com.example.test.utils.RequestJsonUtils;
import com.example.test.vo.ReplyVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @program: test
 * @description: 人脸识别
 * @author: qiu bo yang
 * @create: 2020-10-09 16:19
 **/
@Slf4j
@Service
public class FaceRecognitionServiceImpl implements IFaceRecognitionService {
    @Autowired
    private SnEquipMapper snEquipMapper;
    @Autowired
    private SnPersonMapper snPersonMapper;

    /**
     * 设备人员命令
     *
     * @param request
     * @param response
     */
    @Override
    public void personCmd(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = RequestJsonUtils.getRequestJsonObject(request);
        log.info("personCmd请求数据：{}", jsonObject);
        if (jsonObject != null && StringUtils.isNotEmpty(jsonObject.getString("sn"))) {
            String sn = jsonObject.getString("sn");
            SnEquip snEquip = snEquipMapper.selectSnEquipBySn(sn);
            //启用上传人脸模板
            if (snEquip != null) {
                if (AddStatusEnums.OPEN.getCode().equals(snEquip.getAddStatus())) {
                    SnPerson snPerson = new SnPerson();
                    snPerson.setUploadStatus(UploadStatusEnums.NO_UPLOAD.getCode());
                    List<SnPerson> snPersonList = snPersonMapper.selectSnPersonList(snPerson);
                    if (snPersonList.size() > 0) {
                        for (SnPerson person : snPersonList) {
                            person.setUploadStatus(UploadStatusEnums.YES_UPLOAD.getCode());
                            person.setUpdateDate(new Date());
                            person.setCmd("add");
                        }
                        ReplyVo replyVo = new ReplyVo();
                        replyVo.setSuccess(true);
                        replyVo.setMsg("消息成功");
                        replyVo.setSn(sn);
                        replyVo.setData(snPersonList);
                        responseResult(response, replyVo);
                        snPersonMapper.updateSnPersonList(snPersonList);
                    } else {
                        snEquip.setAddStatus(AddStatusEnums.CLOSE.getCode());
                        snEquip.setUpdateDate(new Date());
                    }
                    snEquip.setFaceCount(jsonObject.getInteger("faceCount"));
                    snEquip.setPersonCount(jsonObject.getInteger("personCount"));
                    snEquipMapper.updateSnEquip(snEquip);

                    //清空所有人员信息
                } else if (ClearStatusEnums.OPEN.getCode().equals(snEquip.getClearStatus())) {
                    List<Map<String, Object>> mapList = new ArrayList<>();
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", "-1");
                    map.put("cmd", "clearAll");
                    map.put("name", "全部人员");
                    map.put("clearRecord", "true");
                    mapList.add(map);
                    ReplyVo replyVo = new ReplyVo();
                    replyVo.setSuccess(true);
                    replyVo.setMsg("消息成功");
                    replyVo.setSn(sn);
                    replyVo.setData(mapList);
                    responseResult(response, replyVo);
                    snEquip.setClearStatus(ClearStatusEnums.CLOSE.getCode());
                    snEquipMapper.updateSnEquip(snEquip);
                } else {
                    snEquip.setFaceCount(jsonObject.getInteger("faceCount"));
                    snEquip.setPersonCount(jsonObject.getInteger("personCount"));
                    snEquipMapper.updateSnEquip(snEquip);
                }

                List<Map<String, Object>> mapList = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                map.put("id", "-1");
                map.put("cmd", "clearAll");
                map.put("name", "全部人员");
                map.put("clearRecord", "true");
                mapList.add(map);
                ReplyVo replyVo = new ReplyVo();
                replyVo.setSuccess(true);
                replyVo.setMsg("消息成功");
                replyVo.setSn(sn);
                replyVo.setData(mapList);
                responseResult(response, replyVo);
                snEquip.setClearStatus(ClearStatusEnums.CLOSE.getCode());
                snEquipMapper.updateSnEquip(snEquip);
            }
        }
    }

    /**
     * 识别图片推送
     *
     * @param request
     * @param response
     */
    @Override
    public void recordPicture(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        MultipartHttpServletRequest multipartRequest = null;
        if (request instanceof MultipartHttpServletRequest) {
            multipartRequest = (MultipartHttpServletRequest) request;
        } else if (request instanceof ShiroHttpServletRequest) {
            ShiroHttpServletRequest shirRequest = (ShiroHttpServletRequest) request;
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
            multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shirRequest.getRequest());
        } else if (request instanceof DefaultMultipartHttpServletRequest) {
            multipartRequest = (MultipartHttpServletRequest) request;
        }
        MultipartFile pictureFile = multipartRequest.getFile("file");
        String url = doUploadFile(pictureFile);
        log.info("recordPicture请求头数据：{},图片文件：{}", map, pictureFile);
        ReplyVo replyVo = new ReplyVo();
        replyVo.setSuccess(true);
        replyVo.setMsg("图片推送成功");
        replyVo.setRegPicture(url);
        responseResult(response, replyVo);
    }

    /**
     * 上传文件
     *
     * @param file
     */
    private String doUploadFile(MultipartFile file) {
        String url = "";
        try {
            String resourceLocation = "D:/sn/";
            //获取文件输入流
            InputStream in = file.getInputStream();
            //文件名称
            String fileName = file.getOriginalFilename();
            //路径创建文件夹
            File Folder = new File(resourceLocation);
            if (!Folder.exists()) {
                Folder.mkdirs();
            }
            //获取文件后缀名-类型
            String suffixType = fileName.substring(fileName.lastIndexOf("."));
            //文件上传路径
            String filePath = resourceLocation + System.currentTimeMillis() + suffixType;
            OutputStream os = new FileOutputStream(filePath);
            byte[] b = new byte[1024];
            int num;
            while ((num = in.read(b)) != -1) {
                os.write(b, 0, num);
            }
            in.close();
            os.close();
            url = filePath;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }


    /**
     * 识别记录推送
     *
     * @param request
     * @param response
     */
    @Override
    public void recordNotice(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = RequestJsonUtils.inputStreamToJsonObject(request);
        log.info("recordNotice请求数据：{}", jsonObject);
        ReplyVo replyVo = new ReplyVo();
        if (jsonObject != null) {
            String dataStr = jsonObject.getString("data");
            List<Map<String, Object>> mapList = (List<Map<String, Object>>) JSONArray.parse(dataStr);
            replyVo.setMsg("识别记录推送成功");
            replyVo.setSuccess(true);
            replyVo.setData(mapList);
        } else {
            replyVo.setMsg("识别记录推送失败");
            replyVo.setSuccess(false);
        }
        //消息响应设备
        responseResult(response, replyVo);
    }

    /**
     * 返回结果
     *
     * @param response
     * @param replyVo
     */
    private void responseResult(HttpServletResponse response, ReplyVo replyVo) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSONObject.toJSONString(replyVo));
            writer.flush();
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
